package com.game.base.monitor;


import android.annotation.TargetApi;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.os.Build;

import com.game.base.utils.log.Logger;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 其他应用使用情况监测器 [https://www.jianshu.com/p/e11cdfaf15dc]
 * Created by Su on 2019/6/4.
 */
public class MonitorUtil {

    /**
     * 获取过去一年手机上使用过的App包名
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    public static void getHistoryApps(Context context) {
        Calendar calendar = Calendar.getInstance();
        long endTime = calendar.getTimeInMillis();
        calendar.add(Calendar.YEAR, -1);
        long startTime = calendar.getTimeInMillis();

        UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, startTime, endTime);

        if (usageStatsList != null && !usageStatsList.isEmpty()) {
            List<String> list = new ArrayList<>();
            for (UsageStats usageStats : usageStatsList) {
                list.add(usageStats.getPackageName());
            }

            if (!list.isEmpty()) {
                Logger.d("size：" + list.size());

                for (int i = 0; i < list.size(); i++) {
                    Logger.d("package：" + list.get(i));
                }
            }
        }
    }
}
